package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    /**
     * 未启用
     *
     * @param dishDTO
     */
    @Override
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.ENABLE);
        this.save(dish);
        Long id = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            //菜品口味表flavors缺少菜品id，需要设置菜品id ----------
            //1. 采用Lambda表达式进行菜品id设置
            flavors.forEach(s -> s.setDishId(id));

//            //2. 使用Stream流
//            flavors = flavors.stream().map(s -> {
//                s.setDishId(id);
//                return s;
//            }).collect(Collectors.toList());

            Db.saveBatch(flavors);
        }

    }

    /**
     * 新增菜品
     * 若菜品所在的分类未启用，则自动启用分类
     *
     * @param dishDTO
     */
    @Override
    public void saveWithFlavorWithCategory(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setStatus(StatusConstant.ENABLE);
        this.save(dish);
        Long id = dish.getId();

        /**
         * 添加菜品选择分类时，若该分类未启用，
         * 将未起用的分类启用
         */
        Long categoryId = dish.getCategoryId();
        Category category = Category.builder()
                .id(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
//        categoryMapper.updateById(category);

        Db.updateById(category);


        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (CollectionUtils.isNotEmpty(flavors)) {
            //菜品口味表flavors缺少菜品id，需要设置菜品id ----------
            //1. 采用Lambda表达式进行菜品id设置
            flavors.forEach(s -> s.setDishId(id));

//            //2. 使用Stream流
//            flavors = flavors.stream().map(s -> {
//                s.setDishId(id);
//                return s;
//            }).collect(Collectors.toList());

            Db.saveBatch(flavors);
        }

    }

    /**
     * 菜品分页查询
     *
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult getDishsByPage(DishPageQueryDTO dishPageQueryDTO) {
        Dish dish = new Dish();

        int page = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        String name = dishPageQueryDTO.getName();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();

        BeanUtils.copyProperties(dishPageQueryDTO, dish);
        log.info(dish.toString());
        Page<Dish> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotBlank(name), Dish::getName, name)
                .eq(categoryId != null, Dish::getCategoryId, categoryId)
                .eq(status != null, Dish::getStatus, status)
                .orderByDesc(Dish::getUpdateTime);
        dishMapper.selectPage(pageInfo, qw);


        Page<DishVO> dishVOPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, dishVOPage, "records");

        List<Dish> records = pageInfo.getRecords();
        List<DishVO> dishVOS = records.stream()
                .map(item -> {
                    DishVO dishVO = new DishVO();
                    //将Dish对象拷贝给DishVO对象
                    BeanUtils.copyProperties(item, dishVO);
                    //获取categoryId对应的categoryName
                    Long categoryId1 = item.getCategoryId();
                    Category category = Db.getById(categoryId1, Category.class);
                    dishVO.setCategoryName(category.getName());
                    return dishVO;
                }).collect(Collectors.toList());
        dishVOPage.setRecords(dishVOS);
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getRecords());

    }

    /**
     * 删除菜品
     *
     * @param ids
     */
    @Override
    public void deleteBatch(List<Long> ids) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids)
                .eq(Dish::getStatus, StatusConstant.ENABLE);
        boolean exists = dishMapper.exists(qw);

        if (exists) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        //判断当前菜品是否能够删除---是否被套餐关联了？？
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getDishId, ids);
        List<SetmealDish> list = setmealDishMapper.selectList(queryWrapper);

        if (CollectionUtils.isNotEmpty(list)) {
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //删除菜品表中的菜品数据
        log.info("deleted...");
        this.removeBatchByIds(ids);//后绪步骤实现
        // 删除菜品关联的口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorQueryWrapper.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(dishFlavorQueryWrapper);
    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = this.getById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> dishFlavors = dishFlavorMapper.selectList(queryWrapper);
        dishVO.setFlavors(dishFlavors);
        return dishVO;
    }

    @Override
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);

//        this.updateById(dish);
        Long id = dish.getId();
        List<DishFlavor> flavors = dishDTO.getFlavors();

        LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        dishFlavorMapper.delete(queryWrapper);

        this.updateById(dish);


        if (CollectionUtils.isNotEmpty(flavors)) {
            //菜品口味表flavors缺少菜品id，需要设置菜品id ----------
            //1. 采用Lambda表达式进行菜品id设置
            flavors.forEach(s -> s.setDishId(id));

//            //2. 使用Stream流
//            flavors = flavors.stream().map(s -> {
//                s.setDishId(id);
//                return s;
//            }).collect(Collectors.toList());

            Db.saveBatch(flavors);
        }
    }

    @Override
    public void updateStatus(Integer status, long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);
    }

    @Override
    public List<Dish> getDishsByCategoryId(Long categoryId) {
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId,categoryId)
                .eq(Dish::getStatus,StatusConstant.ENABLE);
        List<Dish> list = this.list(qw);

        return list;
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotBlank(dish.getName()), Dish::getName, dish.getName())
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(dish.getStatus() != null, Dish::getStatus, dish.getStatus())
                .orderByDesc(Dish::getUpdateTime);
        List<Dish> dishList = dishMapper.selectList(qw);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            LambdaQueryWrapper<DishFlavor> qw1 = new LambdaQueryWrapper<>();
            qw1.eq(DishFlavor::getDishId,d.getId());
            List<DishFlavor> flavors = dishFlavorMapper.selectList(qw1);

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}